package com.tanhua.server.interceptor;

import com.tanhua.db.User;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @version 新增自定义拦截器
 * @author： xtr
 * @date： 2021-03-07 17:20
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入前置拦截处理器");
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)){
            // token 不为空
            User user = userService.getUserByToken(token);
            if (user != null) {
                // redis中有值，则将用户信息存入当前线程
                log.info("redis中的用户信息======== {}", user);
                UserHolder.setUser(user);
                return true;
            }
        }
        // 没值返回401状态码
        response.setStatus(401);
        return false;
    }
}
